package cn.itsource.shiro.permissionFilter;

import net.sf.json.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义权限过滤类,覆写拒绝访问方法,实现ajax和普通方式访问的拒绝形式
 * @author xjh
 * @date 2020/3/6 12:08
 */
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse) response;
        /*获取前端服务器的请求信息,判断是否预检请求*/
        if(req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            /*预检请求则放行*/
            resp.setStatus(HttpStatus.SC_OK);
            return true;
        }
        //前端Ajax请求时requestHeader里面带一些参数，用于判断是否是前端的请求
        String ajaxHeader = req.getHeader("X-Requested-With");
        System.out.println(req.getHeader("X-TOKEN"));
        if (ajaxHeader != null || req.getHeader("X-TOKEN") != null) {
            //前端Ajax请求，则不会重定向
            resp.setHeader("Access-Control-Allow-Origin",  req.getHeader("Origin"));
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setContentType("application/json; charset=utf-8");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            /*json输出,相当于@ResponseBody*/
            JSONObject result = new JSONObject();
            result.put("msg", "权限不足！");
            result.put("success", false);
            out.println(result);
            out.flush();
            out.close();
            return false;
        }
        return super.onAccessDenied(request, response);

    }
}